// <editor-fold defaultstate="collapsed" desc="GNU GPLv3 Header">
/*
 * File:   Main.java
 *
 * Copyright (C) 2013 Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * Copyright (C) 2013 David Megias Jimenez <dmegias@uoc.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
// </editor-fold>
package pcms16leoriolpareraembedderalaw;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import uoc.libcompression.G711.AlawDecoder;
import uoc.libcompression.G711.AlawEncoder;
import uoc.libwatermarking.LSB.LSBByte;
import uoc.libwatermarking.sync.FrameOriented.SintSext;
import uoc.libwave.WaveFormatNonPCMByteAlaw;
import uoc.libwave.WaveFormatPCMShort;

/**
 *
 * @author Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * @version 1.0
 * @since 2013-09-09
 */
public class Main {

    private static short FRAME_SIZE = 256;
    /* Syn params*/
    private static int SYN_MESSAGE = 0x4b871e2d;
    private static int SYN_NBITS = 32;
    private static int SYN_SAMPLES_PER_BIT = 4;
    /* Mark params*/
    private static int MARK_BITS_TO_CODE = 8;
    private static int MARK_SPEC_SAMPLES_PER_BIT = 32;
    private static byte MARK_KEY = 7;

    /**
     *
     * @param frame
     * @param start
     * @param grade
     *
     * @since 2013-08-19
     */
    private static void embedMethod(List<Short> lframe, byte k, int grade) {
        boolean bit = false;
        byte bits = k;
        int nextBlock = 0;
        // watermarking
        for (int i = 0; i < MARK_BITS_TO_CODE; i++) {
            bit = (bits & 0x01) == 0x01;
            bits = (byte) (bits >> 1);
            hideBit(lframe, nextBlock, MARK_SPEC_SAMPLES_PER_BIT, bit);
            nextBlock += MARK_SPEC_SAMPLES_PER_BIT;
        }
    }

    /**
     *
     * @param frame
     * @param start
     * @param size
     * @param i
     *
     * @since 2013-08-19
     */
    private static void hideBit(List<Short> frame, int start, int size, boolean _bit) {
        short sample, expanded;
        byte compressed, watermaked;
        LSBByte lsb = new LSBByte();
        AlawDecoder alawDecoder = new AlawDecoder();
        AlawEncoder alawEncoder = new AlawEncoder();
        for (int i = 0; i < size; i++) {
            // from 16 bits-signed to 13 bits-signed
            sample = (short) (frame.get(start + i) >> 3);
            // get the compressed value
            compressed = alawEncoder.compress(sample);
            // apply the watermark
            watermaked = lsb.embed(compressed, _bit);
            // expand the compressed value
            expanded = alawDecoder.expand(watermaked);
            // from 13 bits-signed to 16 bits-signed
            expanded <<= 3;
            // store the expanded element
            frame.set(start + i, expanded);
        }
    }

    /**
     *
     * @param args the command line arguments
     *
     * @since 2013-08-19
     */
    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("Must supply filenames:");
            System.err.println("java -jar PCM-S16-LE-OriolParera-embedder.jar"
                    + " input.wav output.wav");
            System.exit(1);
        }
        String strSrcFilePath = args[0];
        String strDstFilePath = args[1];
        try {
            // Load the wave file
            WaveFormatPCMShort waveData = new WaveFormatPCMShort(strSrcFilePath);

            // Variables initalization
            short wChannel = (short) 1;
            int num_frames = waveData.getNumSamples() / FRAME_SIZE;
            int dbgrade = 10;
            List<Short> lframe = new ArrayList<Short>();
            byte k = MARK_KEY;
            SintSext watermark_sync = new SintSext(SYN_MESSAGE, SYN_NBITS,
                    SYN_SAMPLES_PER_BIT);
            byte[][] compressed = new byte[wChannel][waveData.getNumSamples()];
            AlawEncoder alawEncoder = new AlawEncoder();

            // for each frame .. each frame has MARK_SAMPLES samples.
            for (int i = 0; i < num_frames; i++) {
                // Get frame from samples
                waveData.getFrame(i * FRAME_SIZE, FRAME_SIZE, wChannel, lframe);
                if (i == 100 || i == 10 || i == 500) { // add sync mark
                    // add the sync mark at the end of the frame
                    watermark_sync.putSynMark(lframe);
                }
                if (i == 101 || i == 11 || i == 501) { // add watermark
                    embedMethod(lframe, k, dbgrade);
                    k *= 4;
                }
                // convert PCM frame to A-law frame
                for (int j = 0; j < lframe.size(); j++) {
                    compressed[wChannel-1][(i * FRAME_SIZE) + j] =
                            alawEncoder.compressTransmission((short)(lframe.get(j) / 8));
                }
                // Clear frame
                lframe.clear();
            }
            // save the wave file
            WaveFormatNonPCMByteAlaw waveDataAlaw =
                    new WaveFormatNonPCMByteAlaw(compressed, waveData.getNumSamples(),
                    waveData.getWChannel(), waveData.getDwSamplesPerSec());
            // save the wave file
            waveDataAlaw.saveToFile(strDstFilePath);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
